<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Search Demo</title>
	
	<script type="text/javascript" src="biojs/dependencies/jquery/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="biojs/dependencies/jquery/jquery-ui-1.8.2.custom.min.js"></script>
	<script type="text/javascript" src="biojs/dependencies/jquery.dataTables.min.js"></script>
	<script type="text/javascript" src="biojs/dependencies/jquery.multiselect.min.js"></script>
	
	<script language="JavaScript" type="text/javascript" src="biojs/Biojs.js"></script>
	<script language="JavaScript" type="text/javascript" src="biojs/Biojs.Autocomplete.js"></script>
	<script language="JavaScript" type="text/javascript" src="biojs/Biojs.TagCloud.js"></script>
	<script language="JavaScript" type="text/javascript" src="biojs/Biojs.QueryPreview.js"></script>
	<script language="JavaScript" type="text/javascript" src="biojs/Biojs.Table.js"></script>

    <link href="css/demo.css" rel="stylesheet" type="text/css"/>
    <link href="biojs/css/biojs.Autocomplete.css" rel="stylesheet" type="text/css"/>
    <link href="biojs/css/biojs.TagCloud.css" rel="stylesheet" type="text/css"/>
    <link href="biojs/css/biojs.QueryPreview.css" rel="stylesheet" type="text/css"/>
    <link href="biojs/css/biojs.Table.css" rel="stylesheet" type="text/css" />
    <link href="biojs/css/smoothness/jquery-ui-1.8.18.custom.css" rel="stylesheet" type="text/css" />
	
	<script language="JavaScript" type="text/javascript">//<![CDATA[
	    window.onload = function() {
	    	
	    	window.autocomplete = new Biojs.Autocomplete({
			    input: $('#searchinput'),
			    arrowType: Biojs.Autocomplete.ARROW_TOP_MIDDLE,
			    fields: ['Producto','PrincipioActivo']
			});
			
			window.preview = new Biojs.QueryPreview({
			    input: $('#searchinput'),
			    arrowType: Biojs.Autocomplete.ARROW_TOP_MIDDLE
			});

			if ( getUrlVars()["producto"] || getUrlVars()["componente"]  ) {
				doSearch(getUrlVars());
			} 
			
			// Atocompletion 
			autocomplete.onItemSelected(function(e){			
				showPreview( e.category, e.text );
			});
			
			// Any change in search box
			$('#searchinput').keyup(function(e){
				if ( status != stateMachine.START ) {
					start();
				}
			});

			preview.onItemSelected(function(e){			
				applyFilter(e.category,e.text);
			});
			
			$('#menu-trigger').click(function(){
				$(this).next('#menu-content').slideToggle();
				$(this).toggleClass('active');					
				
				if ($(this).hasClass('active')) $(this).find('span').html('&#x25B2;');
				else $(this).find('span').html('&#x25BC;');
			});
			
			$.map( columnsForFiltering, function (e,i) {
				$('#filtering #fieldName').append('<option value="' + e + '">' + e + '</option>');
			});

			$('#filtering #fieldName').change(function(){
				$('#filtering #fieldValue').val('');
				window.autocomplete2.setFields([$('#filtering #fieldName').val()]);

			});
			
			window.autocomplete2 = new Biojs.Autocomplete({
			    input: $('#filtering #fieldValue'),
			    arrowType: Biojs.Autocomplete.ARROW_TOP_MIDDLE,
			    minInputChars: 0,
			    fields: [$('#filtering #fieldName').val()]
			});
			
			autocomplete2.onItemSelected(function(e){			
				applyFilter(e.category,e.text);
				$('#menu-trigger').click();
			});

			start();
	    };
	    
	    var searchingFor;
    	var autocomplete, preview, results;
	    var status = 0;
    	var stateMachine = {
    			START: 0,
    			AUTOCOMPLETED: 1,
    			FILTERED: 2,
    			SHOW_RESULTS: 3
    	};
    	var columnNames = [ 
         	  "Expediente",
         	  "Producto",
         	  "Titular",
         	  "Registro",
         	  "Expedicion",
         	  "Vencimiento",
         	  "Estado",
         	  "Consecutivo",
         	  "Cantidad1",
         	  "Presentacion",
         	  "Estado",
         	  "FechaActivo",
         	  "FechaInactivo",
         	  "Unidad",
         	  "Atc",
         	  "PrincipioActivo",
         	  "Via",
         	  "Concentracion",
         	  "Principio Activo",
         	  "Medida",
         	  "Cantidad",
         	  "Referencia",
         	  "Forma",
         	  "Fabricante",
         	  "Modalidad"
        ];
    	
    	var columnsForFiltering = [ 
           	  "Presentacion",
           	  "Estado",
           	  "Unidad",
           	  "Via",
           	  "Concentracion",
           	  "Medida",
           	  "Referencia",
           	  "Fabricante",
           	  "Forma"
    	];
	    
	    function start() {
    		status = stateMachine.START;
	    	preview.hide();
	    	preview.setEnabled(false);
	    	autocomplete.setEnabled(true);
	    	$('#filters').children().remove();
	    	$('#filtersMenu').hide();
	    }
	    
	    function showPreview( category, text ) {
	    	status = stateMachine.AUTOCOMPLETED;
	    	autocomplete.hide();
			autocomplete.setEnabled(false);
			preview.setEnabled(true);
			//preview.show();
			$('#category').val( category );
	    }
	    
	    function applyFilter(fieldName, fieldValue) {
	    	status = stateMachine.FILTERED;
	    	preview.hide();
	    	
	    	var filter = $('<span class="filter '+fieldName+'">'+ fieldValue +'</span>')
	    		.click(function(){
	    			$(this).remove();
	    		})
	    		.appendTo('#filters');
	    	
// 	    	$('<span class="close-btn-18" title="Close">Close</span>')
// 				.click(function(){
// 					filter.remove();
// 				})
// 				.hide()
// 				.prependTo(filter);
	    	
	    }
	    
	    function showResults(){
	    	
	    	var userQuery = buildQuery();
	    	
	    	if ( !Biojs.Utils.isEmpty(userQuery)  ) {
	    		
	    		$('.searchform').animate({'margin-top':'20px'});
	    		$('#table').html('');
	    		$('#examples').remove();
	    		
	    		status = stateMachine.SHOW_RESULTS;

                results = new Biojs.Table({
    				target: "table",
    				dataSet: {
    				    url: 'sim/query.php?'+userQuery,
    				    paramsMap: { "iDisplayStart": "start", "iDisplayLength": "length" },
    				    filter: false
    				},
    				rowSelection: false,
    				showColumnSelector: false,
                    pageLength: 10,
                    columns: columnNames,
                    hideColumns: [
                          0,2,4,5,6,7,8,10,11,12,13,14,15,17,20,21,24
                    ]
    			});
                
                $('#filtersMenu').show();

                Biojs.console.log(userQuery);
 
            }
	    }

	    function doSearch( inputQuery ) {
            
            if ( !Biojs.Utils.isEmpty(inputQuery) ) {            	
            	
            	if (inputQuery.hasOwnProperty('producto')) {
            		$('.searchbox #searchinput').val(inputQuery['producto']);
                	$('.searchbox #category').val('producto');
                	showPreview('producto',inputQuery['producto']);

            	} else {
            		$('.searchbox #searchinput').val(inputQuery['componente']);
                	$('.searchbox #category').val('componente');
                	showPreview('componente',inputQuery['componente']);
            	}
            	
            }

            showResults();
            
	    } 
            
        function buildQuery() {
        	var text = $('.searchbox #searchinput').val();  
        	var category = $('.searchbox #category').val();
        	var query;
        	
        	if ( "producto" == category.toLocaleLowerCase() ) {
        		query = "producto=";
        	} else {
        		query = "componente=";
        	}
        	
        	query += escape(text);

        	// Filtering 
        	for ( i in columnNames ) {
        		
        		var str = "";
        		var filters = $( '.searchbox #filters' ).children( '.' + columnNames[i] );
        		
        		$.map( filters, function(e, i) {
            		str += escape( $(e).text() ) + ';';
            	});
        		
        		if ( str.length > 0 ) {
            		query += '&'+columnNames[i]+'='+str;
            	}
        	}
        	
        	return query;
        }
        

	    function getUrlVars() {
    		var vars = {};
		    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		        vars[key] = value;
		    });
		    return vars;
		}

	   //]]>
	</script>

</head>
<body>
	<div id="header" class="grid12 first">
		<div class="grid12 first searchbox">
			<form class="searchform" onsubmit="doSearch();" action="#">
				<input id="searchinput" class="searchfield" type="text" value="" onfocus=";" onblur=";" />
				<input id="category" type="hidden" value="" />
				<button type="submit">Buscar</button>
				<div id="filters"></div>
			</form>
	        <span id="examples"> Examples: <a onclick="doSearch({producto:'acetaminofen tabletas'});" style="cursor: pointer;">acetaminofen</a>, <a onclick="doSearch({componente:'ibuprofeno'});" style="cursor: pointer;">ibuprofeno</a></span>
		</div>
	</div>

	<div class="grid12 clearfix first">
		<div id="message" style="display:none;" class="grid12"></div>
		<div id="filtersMenu" style="display:none;" class="grid12">
			<ul class="menu">
				<li id="filtering">
					<a id="menu-trigger" href="#">
						Filtrar resultados <span>▼</span>
					</a>
					<div id="menu-content">
						<form>
							<fieldset id="inputs">
								<select id="fieldName" name="Field"></select>
								<input id="fieldValue" type="text" name="Value" autocomplete="off"/>
							</fieldset>
						</form>
					</div>                     
				</li>
			</ul>
		</div>
		<div id="table" class="grid12 first"></div>
	</div>
	
</body>
</html>